// pages/confirm_order/confirm_order.js 
let feedbackApi = require('../common/showToast.js');
const getToken= require('../../utils/get_token.js');
let memberId, openId = '', tuanId='',hebiRedFlag;
const ckToken = async (that) => {//token确认
  let nTime = Math.floor(new Date().getTime() / 1000);
  let oldTime = wx.getStorageSync('ntime') || 0;
  if (nTime < oldTime)//现在的时间小于到期时间
  {
    thou(that);
  } else {
    let tokens = await getToken.getToken();
    thou(that);
  }
}
const thou = (that) => {//token没有失效时执行的代码
  getA(that);
  defaltAdd(that);
  if (openId == '') {
    getToken.getOpenId(function (res) {
      wx.setStorageSync('openId', res.data.openId);
      openId = res.data.openId;
    });
  }
}
const defaltAdd = function (that) {
  let params = ['common/receiver/list', {"id": memberId}]
  getToken.getData(function (res) {
    console.log(res.data);
    if (res.data.lists.length > 0) {
      that.setData({
        name: res.data.lists[0].name,
        phone: Number(res.data.lists[0].mobile)
      })
    }	
  }, ...params)
};
const getA = (that) => {//获取团列表
  let params = [ 'shop/pingTuan/gtmll', {"tuanId":tuanId,"logo":false}]
  getToken.getData(function (res) {
    console.log(res.data)
    let datas = res.data;
    datas.address = JSON.parse(datas.address);
    datas.cityName = datas.address.areaStore + datas.address.address;
    let creatime = datas.endTime;
    let getTime = new Date().getTime();
    let sTime = (creatime - getTime) / 1000;
    fresh(that, sTime);
    that.data.inset=setInterval(function () {
       sTime--;
      fresh(that, sTime)
   }, 1000)
    that.setData({gtm: datas})
  }, ...params)
};
const adzo=function(num) {
	if (num < 10)
		return ('0' + num);
	else
		return num;
}
const fresh=function(that,data){
	if (data <= 0) {
    that.data.times =`截止时间:00:00:00`;
	} else {
    let h = adzo(parseInt(data / 3600));
    let m = adzo(parseInt((data / 60) % 60));
    let s = adzo(parseInt(data % 60));
		that.data.times =`截止时间:${h}:${m}:${s}`;
  }
  that.setData({
    times:that.data.times
  })
}
const jia=function(that,id,limit){//数量加事件 limit是限制的值，
  that.data.ctpood.allNum = that.data.proList.reduce(function (prev, cur) {
     return cur.num + prev;
  }, 0); 
  if(limit>that.data.ctpood.allNum){//当前总数小于限制数
    for(let i=0;i<that.data.proList.length;i++){
      if(id==that.data.proList[i].id){
         that.data.proList[i].num+=1;
         that.data.ctpood.allNum+=1;
      }
    }
    that.data.ctpood.allMoney = that.data.proList.reduce(function (prev, cur) {
      let oMoney=(cur.intPinPrice/100)*cur.num;
      return oMoney + prev;
    }, 0);
    that.data.ctpood.allMoney=that.data.ctpood.allMoney.toFixed(2);
    that.setData({ctpood:that.data.ctpood,proList:that.data.proList})
  }
}
const jian=function(that,id,limit){//数量加事件 limit是限制的最小值，
  that.data.ctpood.allNum = that.data.proList.reduce(function (prev, cur) {
     return cur.num + prev;
  }, 0); 
  if(limit<that.data.ctpood.allNum){
    for(let i=0;i<that.data.proList.length;i++){
      if(id==that.data.proList[i].id){
         if(that.data.proList[i].num>0){
          that.data.proList[i].num-=1;
          that.data.ctpood.allNum-=1;
         }
      }
    }
    that.data.ctpood.allMoney = that.data.proList.reduce(function (prev, cur) {
      let oMoney=(cur.intPinPrice/100)*cur.num;
      return oMoney + prev;
    }, 0);
    that.data.ctpood.allMoney=that.data.ctpood.allMoney.toFixed(2);
    that.setData({ctpood:that.data.ctpood,proList:that.data.proList})
  }
}
const gets=function(that,num){
  that.data.proList[0].num=Number(num);
  that.data.ctpood.allMoney=that.data.proList[0].num*(that.data.proList[0].intPinPrice/100);
  that.data.ctpood.allMoney=that.data.ctpood.allMoney.toFixed(2);
  that.setData({proList: that.data.proList,ctpood:that.data.ctpood})
}
Page({

  /**
   * 页面的初始数据
   */
  data: {
    name: '',
    phone: '',
    limitA: 1,
    memberId: '',
    memo: '',
    boolT: true,
    loading: false,
    disabled: false,
    times:'',
    inset:null,
    productId:'',
    ctpood:{},
    proList:[],
    gtm:{},
    smList:[]
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let that = this;
    tuanId = options.tuanId;
    openId = wx.getStorageSync('openId') || '';
    memberId = wx.getStorageSync('memberId');
    hebiRedFlag= wx.getStorageSync('hebiRedFlag') || '';
    that.data.ctpood= wx.getStorageSync('ctpood') || '';
    console.log(that.data.ctpood)
    if(that.data.ctpood.zt){//自提商品
        that.data.smList=[{'id':2,'name':'批发方式','type':'拼团购买','sm':'团长开团，邀请好友参团，拼团成功，商家发货','img':'../../image/xiala.png','show':false}]
    }else{
        that.data.smList=[
          {'id':1,'name':'配送方式','type':'用户自提','sm':'商品统一打包快递配送至团长收货地址，团员自取','img':'../../image/xiala.png','show':false},
          {'id':2,'name':'批发方式','type':'拼团购买','sm':'团长开团，邀请好友参团，拼团成功，商家发货','img':'../../image/xiala.png','show':false}]
    }
    if(that.data.ctpood.limit>0){
      that.data.limitA=that.data.ctpood.limit;
    }else{
      that.data.limitA=that.data.ctpood.lastNum;
    }
    for(let i=0;i<that.data.ctpood.tallList.length;i++){
      if(that.data.ctpood.tallList[i].num>0){
        if(that.data.ctpood.twogShow){
          that.data.ctpood.tallList[i].name=`${that.data.ctpood.tallList[i].speciValueStoreList[0].name}+${that.data.ctpood.tallList[i].speciValueStoreList[1].name}`;
        }
        that.data.proList.push(that.data.ctpood.tallList[i]);
      }
    }
    that.setData({
      ctpood:that.data.ctpood,
      limitA:that.data.limitA,
      proList:that.data.proList,
      smList:that.data.smList
    })
    ckToken(that);
  },
  /**
 * 生命周期函数--监听页面卸载
 */
onUnload: function () {
  let that = this;
  clearInterval(that.data.inset);
},
spend:function(e){//展示框
  let that = this;
  let id = e.currentTarget.dataset.id;
  that.data.smList.forEach(function(ele,index,arr){
      if(id==ele.id){
        ele.show=!ele.show;
        if(ele.show){
          ele.img='../../image/shouhui.png';
        }else{
          ele.img='../../image/xiala.png';
        }
      }
  })
  that.setData({
    smList:that.data.smList
  })
},
jiaB(e){//单独购买数量加事件
  let that = this;
  let id = e.currentTarget.dataset.id;
  jia(that,id,that.data.limitA)
},
jianB(e){//单独购买数量减事件
  let that = this;
  let id = e.currentTarget.dataset.id;
  jian(that,id,1);
},
  bindKeyInput: function (e) {
    let that=this;
    let mNum=e.detail.value;
    let limiMin=1;
    if(mNum!==''){
     if(mNum>that.data.limitA){
        mNum=that.data.limitA
     } 
     if(mNum<limiMin){
       mNum=limiMin
     }
     gets(that,mNum);
    }
  },
  blurInput:function(e){
    let that=this;
    let mNum=e.detail.value;
    let minNum=1;
    if(mNum=='')
    {
      gets(that,minNum);
    }
  },
  nameBlur:function(e){
    let that=this;
    e.detail.value=e.detail.value.replace(/\s/g, "");
    that.setData({
      name: e.detail.value
    })
  },
  phoneBlur: function (e) {
    let that = this;
    e.detail.value = e.detail.value.replace(/\s/g, "");
    that.setData({
      phone: e.detail.value
    })
  },
  submitOrder: function (e) {//参团
    let that = this;
    let myAount = that.data.proList[0].num;//数量
    let phone = that.data.phone;//电话号码
    let name = that.data.name;//姓名
    let productId= that.data.proList[0].productId;
    if(that.data.isbest&&hebiRedFlag!=1){//新人专享，但不是新人 
      feedbackApi.showToast({ title: '新人专享商品，只有新人才能参团', mask: false });
      return false;
    }
    if (name=='')
    {
      feedbackApi.showToast({ title: '请输入收货人姓名', mask: false })//调用 showToast
      return false;
    }
    if (phone == '') {
      feedbackApi.showToast({ title: '请输入手机号', mask: false })//调用 showToast
      return false;
    }
    that.setData({loading: true,disabled: true})
    let url = 'shop/pinTuanPay/wechatPinTuanHxsmTransferSheQuInt';
    let para = '{"openId":"' + openId + '","tuanId":"' + tuanId + '","productId":"' + productId +'","buyCount":' + myAount + ',"membId":"' + memberId + '","phone":"' + phone + '","userName":"' + name + '","memo":"","isMini":"mini"}';			 
    let params = [ 'shop', url, para]
    getToken.pay(function (res) {
      console.log(res.data);
      if (res.data.flag && res.data.flag != "false") {
        wx.requestPayment({
          'timeStamp': res.data.timeStamp,
          'nonceStr': res.data.nonceStr,
          'package': res.data.package,
          'signType': res.data.signType,
          'paySign': res.data.paySign,
          'success': function (res) {
            console.log(res)
            wx.redirectTo({
              url: '/pages/tsucc/tsucc?id=' + that.data.ctpood.pinId + '&tuanid=' + tuanId + '&types=2'
            })
          },
          'fail': function (res) {
            console.log(res)
          }
        })
      } else {
        feedbackApi.showToast({ title: res.data.message, mask: false })//调用 showToast
      }
      that.setData({
        loading: false,
        disabled: false
      })
    }, ...params)
  }

})